#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
主题:转换并同时计算数据
问题: 你需要在数据序列上执行聚集函数（比如 sum() , min() , max() ）， 但是首先你需要先转换或者过滤数据
提示 : 
"""

def recipe1():
    """非常优雅的方式去结合数据计算与转换就是使用一个生成器表达式参数"""
    nums = [1, 2, 3, 4, 5]
    print(f"{nums = }")
    s = sum(x * x for x in nums) # 更加优雅的实现方式，省略了括号
    print(f"{s = }")

def recipe2():
    """Determine if any .py files exist in a directory"""
    import os
    files = os.listdir('./')
    if any(name.endswith('.py') for name in files):
        print('There be python!')
    else:
        print('Sorry, no python.')

def recipe3():
    """Output a tuple as CSV"""
    s = ('ACME', 50, 123.45)
    print(f"{','.join(str(x) for x in s) = }")

def recipe4():
    """Data reduction across fields of a data structure"""
    portfolio = [
        {'name':'GOOG', 'shares': 50},
        {'name':'YHOO', 'shares': 75},
        {'name':'AOL', 'shares': 20},
        {'name':'SCOX', 'shares': 65}
    ]    
    print(f"{portfolio = }")
    min_shares = min(s['shares'] for s in portfolio)
    print(f"{min_shares = }")
    # 另一种方法， 但结果类型不一样
    min_shares = min(portfolio, key=lambda s: s['shares'])
    print(f"{min_shares = }")

def main():
    print('recipe1'.center(20, '*'))
    recipe1()
    print('recipe2'.center(20, '*'))
    recipe2()
    print('recipe3'.center(20, '*'))
    recipe3()
    print('recipe4'.center(20, '*'))
    recipe4()

if __name__ == '__main__':
    main()    